package com.kitty.game.market;


import com.alibaba.fastjson.JSONObject;
import com.kitty.common.cache.RedisService;
import com.kitty.common.db.Db4CommonService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.thread.IdGenerator;
import com.kitty.game.FieldValuePosConst;
import com.kitty.game.ServerService;
import com.kitty.game.attribute.AttrService;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.base.service.BagService;
import com.kitty.game.config.OnlineMall;
import com.kitty.game.config.SpecialItem;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.i18n.I18nId;
import com.kitty.game.identity.IdentityType;
import com.kitty.game.item.service.ChangeCardService;
import com.kitty.game.market.message.to.CardInfoParam;
import com.kitty.game.market.message.vo.MarketTransactionVo;
import com.kitty.game.market.model.Cargo;
import com.kitty.game.market.model.Goods;
import com.kitty.game.market.model.MarketTransactionRecord;
import com.kitty.game.market.model.StallItem;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pet.message.RespPetHost;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.role.message.ReqGeneralNotify;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.AsktaoUtil;
import com.kitty.game.utils.NotifyModules;
import com.kitty.game.utils.NumberUtil;
import com.kitty.game.utils.TimeUtil;
import com.kitty.listener.EventDispatcher;
import com.kitty.listener.EventType;
import com.kitty.listener.event.RemovePetEvent;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.cache.SessionUtils;
import com.kitty.mina.message.Message;
import com.kitty.mina.message.MessagePusher;
import com.kitty.mina.task.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.mina.core.session.IoSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.kitty.game.market.message.ReqBuyFromStall;
import com.kitty.game.market.message.ReqGoodInfo;
import com.kitty.game.market.message.ReqSetStallGoods;
import com.kitty.game.market.message.ReqStallChangePrice;
import com.kitty.game.market.message.ResMarketRecords;
import com.kitty.game.market.message.RespMarketGoodCard;
import com.kitty.game.market.message.RespMarketPetCard;
import com.kitty.game.market.message.RespStallList;
import com.kitty.game.market.message.RespStallMine;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class MarketService {

    @Autowired
    EquipService equipService;
    @Autowired
    PetService petService;
    @Autowired
    BagService bagService;
    @Autowired
    RoleService roleService;
    @Autowired
    MallService mallService;
    @Autowired
    AttrService attrService;
    @Autowired
    ServerService serverService;
    @Autowired
    Dao dao;
    @Autowired
    RedisService redisService;
    int neice;
    /**
     * 集市是否打开 true不开 false 开
     */
    private static boolean isClosed = false;
    private static int minLevel = 0;
    private static int minRechare = 0;

    private int maxValue = 2000000000;

    private ConcurrentMap<Long, Goods> allGoods = new ConcurrentHashMap<>();

    public void init() {
        List<Goods> list = dao.query(Goods.class, Cnd.NEW());
        for (Goods goods : list) {
            goods.doAfterInit();
            equipService.fixEquip(goods.getRoleEquip());
            if (goods.getPet() != null) {
                if (!goods.getPet().isRepairedId()) {
                   goods.getPet().setRepairedId(true);/*原注释*/
                    int newId = SpringUtils.getIdentityService().getNextId(IdentityType.ROLE);
                    goods.getPet().setId(newId);
                }
            }
            allGoods.put(goods.getId(), goods);
        }
        String jishi_state = DataCache.REDIS_DATA.get("jishi_state");
        minLevel = Integer.parseInt(DataCache.REDIS_DATA.get("jishi_min_level"));
        minRechare = Integer.parseInt(DataCache.REDIS_DATA.get("jishi_min_recharge"));
        if("1".equals(jishi_state)){
            isClosed = false;
        }else{
            isClosed = true;
        }
        if (serverService.getServer() != null && serverService.getServer().getId() == 10000){
            isClosed = true;
        }
    }

    public void queryTransactionRecord(Role role) {
        List<MarketTransactionRecord> records = role.getTransactionBox().getBaiTanRecords();
        List<MarketTransactionVo> sellRecords = new ArrayList<>();
        List<MarketTransactionVo> buyRecords = new ArrayList<>();

        for (MarketTransactionRecord record : records) {
            MarketTransactionVo vo = MarketTransactionVo.valueOf(record);
            if (record.getType() > 0) {
                sellRecords.add(vo);
            } else {
                buyRecords.add(vo);
            }
        }

        ResMarketRecords response = new ResMarketRecords();
        response.setBuyList(buyRecords);
        response.setSellList(sellRecords);
        MessagePusher.pushMessage(role, response);
    }


    /**
     * 上架需要的摊位费
     */
    private int getMarketRent(int price) {
        int marketRent = new Double(Math.ceil(price * 0.01)).intValue();
        if (marketRent > 1000000) {
            marketRent = 1000000;
        }
        if (marketRent < 100000) {
            marketRent = 100000;
        }
        return marketRent;
    }

    /**
     * 重新摆摊
     *
     * @param role
     * @param reqGeneralNotify
     */
    public synchronized void upShellAgain(Role role, ReqGeneralNotify reqGeneralNotify) {
        if (!commonVerify(role)) {
            return;
        }
        String idStr = reqGeneralNotify.getStatus();
        String priceStr = reqGeneralNotify.getString();
        int price = Integer.parseInt(priceStr);
        if (price <= 0 || price > maxValue) {
            return;
        }
        int marketRent = getMarketRent(price);
        if (role.getMoney() < marketRent) {
            MessagePusher.pushMessage(role, new RespMsg("你的金钱不足！请到积分商城购买"));
            return;
        }
         long id = Long.parseLong(idStr);
        Goods goods = allGoods.get(id);
        if (goods == null) {
            MessagePusher.pushMessage(role, new RespMsg("物品信息不存在。"));
            return;
        }
        roleService.subtractMoney(role,  marketRent);


        goods.setPrice(price);
        if (isPublicityItem(goods)) {
            goods.setShowEndTime(new Date(System.currentTimeMillis() + getShowEndTime()));
            goods.setEndTime(new Date(System.currentTimeMillis() + 3 * TimeUtil.ONE_DAY));
        } else {
            goods.setShowEndTime(new Date());
            goods.setEndTime(new Date(System.currentTimeMillis() + 2 * TimeUtil.ONE_DAY));
        }
        goods.setStartTime(new Date());
        sendGoodsList(role);
    }

    private long getShowEndTime() {
        return 5 * TimeUtil.ONE_MINUTE;
    }


    public void getGoodsPrice(String itemName, Role role) {
        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        int price = getItemStandardPrice(itemName);

        HashMap<Object, Object> map = new HashMap<>();
        map.put(50, new Double(price * 0.5).intValue());
        map.put(60, new Double(price * 0.6).intValue());
        map.put(70, new Double(price * 0.7).intValue());
        map.put(80, new Double(price * 0.8).intValue());
        map.put(90, new Double(price * 0.9).intValue());
        map.put(100, price);
        map.put(110, new Double(price * 1.1).intValue());
        map.put(120, new Double(price * 1.2).intValue());
        map.put(130, new Double(price * 1.3).intValue());
        map.put(140, new Double(price * 1.4).intValue());
        map.put(150, new Double(price * 1.5).intValue());
        map.put("name", itemName);
        respGeneralNotify.setValue(JSONObject.toJSONString(map));//TODO 这里用JsonUtil转出来的String 不符合客户端要求 客户端需要的数字的key 不带引号
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_STALL_ITEM_PRICE);//摆摊物品价格
        MessagePusher.pushMessage(role, respGeneralNotify);

        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_STALL_BATCH_NUM);//通知客户端集市商品可上架的数量
        int num = equipService.getCount(itemName, false, role);
        respGeneralNotify.setValue(num > 10 ? 10 + "" : num + "");
        MessagePusher.pushMessage(role, respGeneralNotify);
    }

    /**
     * 获得道具标准价格
     *
     * @param itemName
     * @return
     */
    private int getItemStandardPrice(String itemName) {
        MallService mallService = SpringUtils.getBean(MallService.class);
        OnlineMall onlineMall = mallService.getOnlineMallByName(itemName);
        int price = 0;
        if (onlineMall != null) {
            price = onlineMall.getPrice() * 10000;
        } else {
            SpecialItem specialItem = mallService.getSpecialItem(itemName);
            if (specialItem != null) {
                price = specialItem.getPrice();
            } else {
                price = 1800000;
            }
        }
        if (price <= 0) {
            price = 1800000;
        }
        return price;
    }

    /**
     * 提款
     *
     * @param role
     */
    public void takeCash(Role role) {
        if (!commonVerify(role)) {
            return;
        }
        long stallCash = role.getStallCash();
        if (stallCash <= 0) {
            return;
        }
        int money = role.getMoney();
        if (money >= maxValue) {
            return;
        }
        int tiquMoney = 0;
        if (money + stallCash > maxValue) {
            tiquMoney = maxValue - money;
        } else {
            tiquMoney = (int) stallCash;
        }
        log.error("roleId[{}] takeCash {}", role.getRoleId(), tiquMoney);
        role.setStallCash(role.getStallCash() - tiquMoney);
        roleService.addMoney(role, tiquMoney);
        MessagePusher.pushMessage(role, new RespIconCartoon("金钱"));
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("你成功提取了" + AsktaoUtil.getMoneyFormat(tiquMoney) + "#n文钱！"));
        sendGoodsList(role);
    }


    private boolean commonVerify(Role role) {
        if (isClosed) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("集市休市中。");
            MessagePusher.pushMessage(role, respMsg);
            return false;
        }
        if(ServerService.neice!=100){
            if (role.getTotalCharge() <= minRechare || role.getLevel() < minLevel){

                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值或等级不足，无法使用集市功能！！"));
                return false;
            }
        }
        if (role.isBanTrade()) {
            return false;
        }

        return true;
    }

    /**
     * 购买物品
     *
     * @param session
     * @param reqBuyFromStall
     */
    public synchronized void buyGoods(IoSession session, ReqBuyFromStall reqBuyFromStall) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        if (!commonVerify(role)) {
            return;
        }
        long mianbanId = Long.parseLong(reqBuyFromStall.getId());
        int price = reqBuyFromStall.getPrice();
        if (price <= 0) {
            return;
        }
        Goods goods = allGoods.get(mianbanId);
        if (goods == null) {
            MessagePusher.pushMessage(role, new RespMsg("物品信息不存在。"));
            return;
        }
        if (goods.getPrice() != price) {
            return;
        }
        if (role.getMoney() < goods.getPrice()) {
            return;
        }
        if (goods.getEndTime().before(new Date())) {
            return;
        }
        if (goods.getShowEndTime().after(new Date())) {
            return;
        }
        if (goods.getRoleId() == role.getUid()) {
            MessagePusher.pushMessage(session, new RespMsg("不可以购买自己的物品！"));
            return;
        }

        if (goods.getType1().equals("宠物")) {
            if (SpringUtils.getPetService().isEquippedFull(role)) {
                MessagePusher.pushMessage(session, new RespMsg("对不起，你的宠物栏满了，请整理后再来吧。"));
                return;
            }
            Pet pet = goods.getPet();
            try {
                role.getPetBox().addNewPet(pet);
                pet.setHostId(role.getRoleId());
                pet.setHostName(role.getName());
                petService.addLimitTimeDay(pet, 3);
                petService.loadPet(role, pet);
                RespIconCartoon respIconCartoon = new RespIconCartoon();
                respIconCartoon.setType((short) 2);
                respIconCartoon.setName(pet.getName());
                if (pet.getItype() != 0) {
                    respIconCartoon.setParam(pet.getRankItem() + "");
                } else {
                    respIconCartoon.setParam(pet.getIcon() + "");
                }
                MessagePusher.pushMessage(session, respIconCartoon);
                String msg = AsktaoUtil.getMoneyFormat(goods.getPrice());
                MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了" + msg + "#n文金钱，购买了一只#Y" + pet.getName() + "#n。"));
            } catch (Exception e) {
                log.error("", e);
            }
        } else {
            short pos = bagService.getPos(session, false);
            if (pos <= 0) {
                MessagePusher.pushMessage(session, new RespMsg("你的包裹已满，还是整理后再来吧。"));
                return;
            }
            RoleEquip roleEquip = goods.getRoleEquip();
            try {
                roleEquip.setPosition(pos);
                roleEquip.setRoleId(role.getRoleId());
                roleEquip.setEquipValue(FieldValuePosConst.NUM, 1);
                equipService.addRoleEquipLimitTimeDay(roleEquip, 3);
                equipService.add(role, roleEquip);

                // 入包动画
                RespIconCartoon respIconCartoon = new RespIconCartoon();
                respIconCartoon.setName(roleEquip.getName());
                respIconCartoon.setParam(roleEquip.getId() + "");
                MessagePusher.pushMessage(session, respIconCartoon);
                equipService.refreshRoleEquip(role, roleEquip);
                String msg = AsktaoUtil.getMoneyFormat(goods.getPrice());
                MessagePusher.pushMessage(session, new RespNotifyMiscEx("你花费了" + msg + "#n文金钱，购买了一件#Y" + goods.getName() + "#n。"));
            } catch (Exception e) {
                log.error("", e);
            }
        }


        roleService.subtractMoney(role,   goods.getPrice());

        goods.setDelete(true);
        Db4CommonService.getInstance().add2Queue(goods);
        allGoods.remove(mianbanId);

        role.save();

        // 给买方钱
        Role seller = SpringUtils.getPlayerService().getPlayerBy(goods.getRoleId());
        if (SpringUtils.getRoleService().isOnline(seller)) {
            ThreadLocalUtil.addLocalTask(seller, () -> addMoneyToSeller(seller, goods));
        } else {
            addMoneyToSeller(seller, goods);
        }

        log.error("buyGoods {} from {} price {} goodsId {} goodsName {}", role.getRoleId(), seller.getRoleId(), goods.getPrice(), goods.getId(), goods.getName());

        MarketTransactionRecord buyRecord = MarketTransactionRecord.valueOf(goods);
        role.getTransactionBox().addBaiTanRecord(buyRecord);

        Object object = session.getAttribute("baitan_list");
        if (object == null) {
            return;
        }
        marketQuery((ReqGeneralNotify) object, session);
    }

    private void addMoneyToSeller(Role seller, Goods goods) {
        seller.setStallCash(seller.getStallCash() + goods.getPrice());
        MarketTransactionRecord sellRecord = MarketTransactionRecord.valueOf(goods);
        sellRecord.setType((byte) 1);
        seller.getTransactionBox().addBaiTanRecord(sellRecord);
        seller.save();

        log.error("addMoneyToSeller {} goods[{}] [{}] price {} nowMoney {}", seller.getRoleId(),
                goods.getId(), goods.getName(), goods.getPrice(), seller.getStallCash());
    }


    private Message checkItemPrice(String itemName, int price) {
        if (isPublicityItem(itemName)) {
            return null;
        }
        int standardPrice = getItemStandardPrice(itemName);
        int lowPrice = (int) (standardPrice * 0.5);
        int maxPrice = (int) (standardPrice * 1.5);
        if (price < lowPrice) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("道具最低出售价为" + lowPrice);
            return respMsg;
        }
        if (price > maxPrice) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("道具最高出售价为" + maxPrice);
            return respMsg;
        }
        return null;
    }

    /**
     * 判断是否是公式物品
     */

    private boolean isPublicityItem(String itemName) {
        if (itemName.contains("超级黑水晶·"))return false;
        Object obj = MarketDataPool.marketDatas.get(itemName);
        if (obj == null) {
            return false;
        }
        NutMap nutMap = (NutMap) obj;
        String type = nutMap.getString("subClass");
        return "装备".equals(type) || "宠物".equals(type) || "高级首饰".equals(type)  || "天技秘笈".equals(type) || "法宝".equals(type);
    }

    /**
     * 改价格
     *
     * @param session
     * @param req
     */
    public synchronized void updatePrice(IoSession session, ReqStallChangePrice req) {
        Role role = SessionUtils.getRoleBySession(session);
        if (!commonVerify(role)) {
            return;
        }
        if (req.getPrice() < 0) {
            return;
        }
        long goodsId = NumberUtil.longValue(req.getGoods_gid());
        Goods goods = allGoods.get(goodsId);
        if (goods == null) {
            return;
        }
        if (goods.getRoleId() != role.getUid()) {
            return;
        }

        long now = System.currentTimeMillis();
        if (now - goods.getLastUpdatePrice() < TimeUtil.ONE_DAY) {
            return;
        }

        goods.setLastUpdatePrice(now);
        int oldPrice = goods.getPrice();
        int price = req.getPrice();

        // 带属性的超级黑水晶，不需要浮动
        if (!"超级黑水晶".equals(goods.getType1())) {
            Message checkMsg = checkItemPrice(goods.getName(), price);
            if (checkMsg != null) {
                MessagePusher.pushMessage(role, checkMsg);
                return;
            }
        }

        goods.setPrice(price);
        goods.setStartTime(new Date());
        if (isPublicityItem(goods)) {
            goods.setShowEndTime(new Date(System.currentTimeMillis() + getShowEndTime()));
            goods.setEndTime(new Date(System.currentTimeMillis() + 3 * TimeUtil.ONE_DAY));
        } else {
            goods.setShowEndTime(new Date());
            goods.setEndTime(new Date(System.currentTimeMillis() + 2 * TimeUtil.ONE_DAY));
        }
        log.error("roleId[{}] update price {}", role.getRoleId(), oldPrice, price);
        Db4CommonService.getInstance().add2Queue(goods);

        sendGoodsList(role);
    }

    /**
     * 是否是公示道具
     *
     * @return
     */
    public boolean isPublicityItem(Goods goods) {
        String type1 = goods.getType1();
        if ("装备".equals(type1) || "宠物".equals(type1) || "高级首饰".equals(type1)
                || "超级黑水晶".equals(type1) || "天技秘笈".equals(type1) || "法宝".equals(type1)) {
            return true;
        }
        if (goods.getName().contains("超级黑水晶·")) {
            return true;
        }
        String type2 = goods.getType2();
        if ("普通".equals(type2) || "变异".equals(type2)) {
            return true;
        }
        return false;
    }

    /**
     * 撤摊
     *
     * @param session
     * @param req
     */
    public synchronized void removeGoods(IoSession session, ReqGeneralNotify req) {
        Role role = SessionUtils.getRoleBySession(session);
        if (!commonVerify(role)) {
            return;
        }

        long mianbanId = Long.parseLong(req.getStatus());
        short pos = bagService.getPos(session, false);
        if (pos <= 0) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("你的包裹已满，还是整理后再来吧。");
            MessagePusher.pushMessage(session, respMsg);
            return;
        }
        Goods goods = allGoods.get(mianbanId);
        if (goods == null) {
            return;
        }
        if (goods.getRoleId() != role.getId()) {
            log.error("roleId[{}] steal goodsId {}", role.getRoleId(), goods.getId());
            return;
        }
        allGoods.remove(mianbanId);
        goods.setDelete(true);
        Db4CommonService.getInstance().add2Queue(goods);

        // 物品放回原主人背包
        if (goods.getType1().equals("宠物")) {
            Pet pet = goods.getPet();
            log.error("roleId[{}] removeGoods pet {}", role.getRoleId(), pet.getId());
            role.getPetBox().addNewPet(pet);
            petService.loadPet(role, pet);
        } else {
            RoleEquip roleEquip = goods.getRoleEquip();
            roleEquip.setPosition(pos);
            equipService.add(role, roleEquip);

            if ("变身卡".equalsIgnoreCase(roleEquip.getType())) {
                try {
                    SpringUtils.getBean(ChangeCardService.class).saveCard(role, roleEquip);
                } catch (Exception e) {
                    log.error("", e);
                }
            }

            log.error("roleId[{}] removeGoods equip {}", role.getRoleId(), roleEquip.getId());
            equipService.refreshRoleEquip(role, roleEquip);
        }

        role.save();

        sendGoodsList(role);
    }

    /**
     * 货物详情
     *
     * @param session
     * @param reqGoodInfo
     */
    public void goodsInfo(IoSession session, ReqGoodInfo reqGoodInfo) {
        if (isClosed) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("集市休市中。");
            MessagePusher.pushMessage(session, respMsg);
            return;
        }
        Role role = SessionUtils.getRoleBySession(session);
        if(ServerService.neice!=100){
            if (role.getTotalCharge() <= minRechare || role.getLevel() < minLevel){

                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值或等级不足，无法使用集市功能！！"));
                return ;
            }
        }
        String str = reqGoodInfo.getItem_cookie();
        String[] strings = str.split(";");
        Goods goods = allGoods.get(Long.parseLong(strings[0]));
        if (goods == null) {
            MessagePusher.pushMessage(session, new RespMsg("物品信息不存在。"));
            return;
        }
        if (goods.getType1().equals("宠物")) {
            Pet pet = goods.getPet();
            RespMarketPetCard respMarketPetCard = new RespMarketPetCard();
            if (goods.getShowEndTime().after(new Date())) {
                respMarketPetCard.setEndTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
            } else {
                respMarketPetCard.setEndTime(new Long(goods.getEndTime().getTime() / 1000).intValue());
            }
            respMarketPetCard.setGoodId(goods.getMianbanId());
            respMarketPetCard.setList(new ArrayList<>());
            respMarketPetCard.getList().addAll(pet.getAllFields());
            MessagePusher.pushMessage(session, respMarketPetCard);
            return;
        }

        RespMarketGoodCard respMarketGoodCard = new RespMarketGoodCard();
        respMarketGoodCard.setList(equipService.transferList(goods.getRoleEquip().getFields()));
        respMarketGoodCard.setId(strings[0]);
        if (goods.getShowEndTime().after(new Date())) {
            respMarketGoodCard.setTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
        } else {
            respMarketGoodCard.setTime(new Long(goods.getEndTime().getTime() / 1000).intValue());
        }
        MessagePusher.pushMessage(session, respMarketGoodCard);
    }

    private List<Predicate<Goods>> filterConditions(String condition1, String condition2, String condition3, int type) {
        List<Predicate<Goods>> result = new ArrayList<>();
        switch (condition1) {
            case "变身卡":
                result.add(goods -> goods.getType1().equals("变身卡"));
                result.add(goods -> goods.getType2().equals(condition2));
                result.add(goods -> goods.getType3().equals(condition3));
                break;
            case "天技秘笈":
                result.add(goods -> goods.getType1().equals("天技秘笈"));
                result.add(goods -> goods.getType2().equals(condition2));
                break;
            case "高级首饰": {
                result.add(goods -> goods.getType1().equals("高级首饰"));
                result.add(goods -> goods.getType2().equals(condition2));
                int type3 = Integer.parseInt(condition3);
                result.add(goods -> goods.getLevel() == type3);
                break;
            }
            case "低级首饰": {
                result.add(goods -> goods.getType1().equals("低级首饰"));
                result.add(goods -> goods.getType2().equals(condition2));
                int type3 = Integer.parseInt(condition3);
                result.add(goods -> goods.getLevel() == type3);
                break;
            }
            case "装备": {
                result.add(goods -> goods.getType1().equals("装备"));
                result.add(goods -> goods.getType2().equals(condition2));
                int type3 = Integer.parseInt(condition3);
                result.add(goods -> goods.getLevel() >= type3 && goods.getLevel() <= type3 + 9);
                break;
            }
            case "魂器": {
                result.add(goods -> goods.getType1().equals(condition2));
//                result.add(goods -> goods.getType2().equals(condition2));
                break;
            }
            case "法宝":
                result.add(goods -> goods.getType1().equals("法宝"));
                result.add(goods -> goods.getName().equals(condition2));
                switch (condition3) {
                    case "金相性":
                        result.add(goods -> goods.getXiangxin() == 1);
                        break;
                    case "木相性":
                        result.add(goods -> goods.getXiangxin() == 2);
                        break;
                    case "水相性":
                        result.add(goods -> goods.getXiangxin() == 3);
                        break;
                    case "火相性":
                        result.add(goods -> goods.getXiangxin() == 4);
                        break;
                    case "土相性":
                        result.add(goods -> goods.getXiangxin() == 5);
                        break;
                }
                break;
            case "未鉴定装备": {
                result.add(goods -> goods.getType1().equals("未鉴定装备"));
                result.add(goods -> goods.getType2().equals(condition2));
                int type3 = Integer.parseInt(condition3);
                result.add(goods -> goods.getLevel() >= type3 && goods.getLevel() <= type3 + 9);
                break;
            }
            case "宠物":
                result.add(goods -> goods.getType1().equals("宠物"));
                result.add(goods -> goods.getType2().equals(condition2));
                break;
            case "装备道具":
                result.add(goods -> goods.getType1().contains("道具"));
                result.add(goods -> goods.getType2().equals(condition2));
                break;
            case "宠物道具":
                result.add(goods -> goods.getType1().equals("宠物道具"));
                result.add(goods -> goods.getType2().equals(condition2));
                result.add(goods -> StringUtils.isBlank(condition3) || goods.getType3().equals(condition3));
                break;
            case "妖石":
                result.add(goods -> goods.getType1().equals("妖石"));
                result.add(goods -> goods.getType2().equals(condition2));
                break;
            case "其他道具":
                if (StringUtils.isNotEmpty(condition3)) {
                    result.add(goods -> goods.getType2().equals(condition3));
                } else {
                    result.add(goods -> goods.getType2().equals(condition2));
                }
                result.add(goods -> goods.getType1().equals("其他道具"));
                result.add(goods -> goods.getType2().equals(condition2));
                break;
            case "超级黑水晶":
                result.add(goods -> goods.getType1().equals("超级黑水晶"));
                result.add(goods -> goods.getType2().equals(condition2));
                result.add(goods -> goods.getType3().equals(condition3));
                break;
            case "天书":
                result.add(goods -> goods.getType1().equals("天书"));
                if (!"天书".equals(condition2)) {
                    result.add(goods -> goods.getName().equals(condition2));
                }
                break;
            default:
                // 未添加的类型默认不显示
                result.add(goods -> false);
                break;

        }

        result.add(goods -> goods.getEndTime().getTime() > new Date().getTime());
        if (type == 1) {
            result.add(goods -> goods.getShowEndTime().getTime() > new Date().getTime());
        } else {
            result.add(goods -> goods.getShowEndTime().getTime() < new Date().getTime());
        }

        return result;
    }

    /**
     *
     *   "type": -25518,
     *    "status": "装备_枪_80",
     *    "string": "1;2;1;price"
     * @param req
     * @param session
     */
    public void marketQuery(ReqGeneralNotify req, IoSession session) {
        if (isClosed) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("集市休市中。");
            MessagePusher.pushMessage(session, respMsg);
            return;
        }
        Role role = SessionUtils.getRoleBySession(session);
        if(ServerService.neice!=100){
            if (role.getTotalCharge() <= minRechare || role.getLevel() < minLevel){

                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值或等级不足，无法使用集市功能！！"));
                return ;
            }
        }
        session.setAttribute("baitan_list", req);
        String[] conditionArray = req.getStatus().split("_");
        String condition1 = conditionArray.length > 0 ? conditionArray[0] : null;
        String condition2 = conditionArray.length > 1 ? conditionArray[1] : null;
        String condition3 = conditionArray.length > 2 ? conditionArray[2] : null;

        String[] pageParams = req.getString().split(";");
        int pageIndex = Integer.parseInt(pageParams[0]);
        byte type = Byte.parseByte(pageParams[1]);
        String sortKey = pageParams.length > 3 ? pageParams[3] : "price";
        int sortType = pageParams.length > 2 ? Integer.parseInt(pageParams[2]) : 1;

        List<Predicate<Goods>> conditions = filterConditions(condition1, condition2, condition3, type);
        Stream<Goods> stream = allGoods.values().stream();

        for (Predicate<Goods> predicate : conditions) {
            stream = stream.filter(predicate);
        }

        int countPerPage = 8;
        List<Goods> targetGoods = stream.collect(Collectors.toList());

        targetGoods.sort((o1, o2) -> {
            if (sortKey.equals("start_time")) {
                if (1 == sortType) {
                    // 升序
                    return o1.getStartTime().compareTo(o2.getStartTime());
                }
                return o2.getStartTime().compareTo(o1.getStartTime());
            }
            if (1 == sortType) {
                // 升序
                return o1.getPrice() - o2.getPrice();
            }
            return o2.getPrice() - o1.getPrice();
        });


        int maxPage = (int) Math.ceil((double) targetGoods.size() / countPerPage);
        pageIndex = Math.max(1, pageIndex);
        pageIndex = Math.min(pageIndex, maxPage);

        int startIndex = (pageIndex - 1) * countPerPage - 1;
        startIndex = Math.max(0, startIndex);
        int endIndex = startIndex + countPerPage;
        endIndex = Math.min(endIndex, targetGoods.size());
        targetGoods = targetGoods.subList(startIndex, endIndex);

        RespStallList response = new RespStallList();
        response.setIs_descending(type);
        response.setPath_str(req.getStatus());
        response.setTotalPage((short) maxPage);
        List<StallItem> list = new ArrayList<>();
        response.setList(list);
        response.setCurrPage((short) pageIndex);
        response.setSell_stage(type);
        response.setSort_key("price");


        for (Goods goods : targetGoods) {
            StallItem stallItem = new StallItem();
            stallItem.setName(goods.getName());
            stallItem.setName(goods.getName());
            stallItem.setId(goods.getMianbanId() + "");
            if (type == 1) {
                stallItem.setStatus((short) 1);
                stallItem.setEndTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
                stallItem.setStartTime(new Long(goods.getStartTime().getTime() / 1000).intValue());
            } else {
                stallItem.setEndTime(new Long(goods.getEndTime().getTime() / 1000).intValue());
                stallItem.setStartTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
                stallItem.setStatus((short) 2);
            }
            stallItem.setPrice(goods.getPrice());
            stallItem.setReq_level(goods.getLevel() <= 1 ? 0 : goods.getLevel());
            stallItem.setAmount((short) goods.getNumber());
            if (goods.getType1().equals("未鉴定装备")) {
                stallItem.setUnidentified((byte) 1);
            } else {
                stallItem.setUnidentified((byte) 0);
            }
            if (goods.getType1().equals("宠物")) {
                Pet pet = goods.getPet();
                stallItem.setPetLevel(pet.getLevel());
                NutMap nutMap = NutMap.NEW();
                nutMap.setv("enchant", pet.getEnchant());
                nutMap.setv("rank", pet.getType());
                nutMap.setv("mount_type", pet.getItype());
                if (pet.getMagRebuildLevel() == 0 && pet.getPhyRebuildLevel() == 0) {
                    nutMap.setv("rebuild_level", 0);// 0未强化 1强化
                } else {
                    nutMap.setv("rebuild_level", 1);// 0未强化 1强化
                }
                nutMap.setv("eclosion", pet.getEclosion());//2羽化
                stallItem.setExtra(Json.toJson(nutMap, JsonFormat.compact()));
                stallItem.setItem_polar(goods.getXiangxin());
            } else if (goods.getType1().equals("法宝")) {
                stallItem.setItem_polar(goods.getXiangxin());
            }
            //判断是不是自己的
            if(role.getRoleId() == goods.getRoleId()){
                stallItem.setIs_my_goods((byte)1);
            }

            list.add(stallItem);
        }
        MessagePusher.pushMessage(session, response);
    }


    /**
     * 物品上架
     *
     * @param session
     * @param req
     */
    public synchronized void upShell(IoSession session, ReqSetStallGoods req) {
        Role role = SessionUtils.getRoleBySession(session);
        if (role == null) {
            return;
        }
        if (!commonVerify(role)) {
            return;
        }
        List<Goods> myGoods = queryMyGoods(role);
        int size = myGoods.size();
        if (size >= getMaxStallNum(role)) {
            return;
        }
        if (req.getPrice() < 0) {
            return;
        }
        if (serverService.getServer().getId() == 10000){
            MessagePusher.pushMessage(role,new RespNotifyMiscEx("跨服试道中，不能摆摊"));
            return;
        }
        if (req.getType() == 2) {
            // 宠物摆摊
            petUpShell(req, session);
            return;
        }
        itemUpShell(req, role);
    }

    /**
     * 宠物摆上摊
     */
    private void petUpShell(ReqSetStallGoods req, IoSession session) {
        int marketRent = getMarketRent(req.getPrice());
        Role role = SessionUtils.getRoleBySession(session);
        if (role.getMoney() < marketRent) {
            return;
        }
        Pet pet = petService.getPetById(req.getInventoryPos(), role);
        if (pet == null) {
            return;
        }
        if (pet.isInStore()) {
            return;
        }


        roleService.subtractMoney(role,  marketRent);
        role.getPetBox().removePet(pet);
        log.error("roleId[{}] upShell pet {}", role.getRoleId(), pet.getId());
        /** 产生一个移除宠物事件 */
        EventDispatcher.getInstance().fireEvent(new RemovePetEvent(EventType.REMOVE_PET, role, pet));

        //消失宠物
        RespPetHost respPetHost = new RespPetHost();
        respPetHost.setPetId(pet.getId());
        MessagePusher.pushMessage(session, respPetHost);

        Goods goods = new Goods();
        goods.setPrice(req.getPrice());
        goods.setLevel(pet.getLevel());
        goods.setXiangxin(pet.getPolar());

        goods.setRoleId(role.getId());
        goods.setName(pet.getName());
        goods.setId(IdGenerator.getNextId());
        goods.setType1("宠物");
        goods.setStartTime(new Date());
        goods.setNumber(1);
        goods.setShowEndTime(new Date(System.currentTimeMillis() + getShowEndTime()));
        goods.setEndTime(new Date(System.currentTimeMillis() + 3 * TimeUtil.ONE_DAY));
        if (pet.getItype() == 1 || pet.getItype() == 2) {
            goods.setType2("精怪/御灵");
        } else if (pet.getType() == 2) {
            goods.setType2("普通");
        } else if (pet.getType() == 3) {
            goods.setType2("变异");
        } else if (pet.getType() == 4) {
            goods.setType2("神兽");
        }
        goods.setPet(pet);

        allGoods.put(goods.getId(), goods);
        role.save();
        Db4CommonService.getInstance().add2Queue(goods);

        sendGoodsList(role);
    }

    private void itemUpShell(ReqSetStallGoods req, Role role) {
        RoleEquip roleEquip = equipService.getRoleEquipByPos(role, (short) req.getInventoryPos());
        if (roleEquip == null) {
            return;
        }
        if (roleEquip.getPosition() != req.getInventoryPos()) {
            return;
        }
        if (roleEquip.isLimit()) {
            return;
        }
        int marketRent = getMarketRent(req.getPrice());
        if (req.getAmount() <= 0) {
            return;
        }
        if (role.getMoney() < marketRent) {
            return;
        }

        int price = req.getPrice();
        // 带属性的超级黑水晶，不需要浮动
        if (!"超级黑水晶".equals(roleEquip.getType())) {
            Message checkMsg = checkItemPrice(roleEquip.getName(), price);
            if (checkMsg != null) {
                MessagePusher.pushMessage(role, checkMsg);
                return;
            }
        }

        Goods goods = new Goods();
        goods.setId(IdGenerator.getNextId());

        if (roleEquip.getType().equals("装备") || roleEquip.getType().equals("高级首饰") || roleEquip.getType().equals("法宝") ||roleEquip.getType().equals("超级黑水晶")) {
            equipService.delRoleEquip(roleEquip, role);
            goods.setRoleEquip(roleEquip);
        } else {
            if (req.getAmount() > 0) {
                int sellNum = req.getAmount();
                sellNum = Math.min(sellNum, 10);
                int currItemNum = roleEquip.queryNum();
                if (currItemNum < sellNum) {
                    log.error("roleId[{}] itemUpShell price error", role.getRoleId());
                    return;
                }
                if (equipService.delEquipNum(role, roleEquip, sellNum) <= 0) {
                    return;
                }
                if (currItemNum > sellNum) {
                    String content = Json.toJson(roleEquip);
                    RoleEquip cloneRoleEquip = Json.fromJson(RoleEquip.class, content);
                    cloneRoleEquip.alterNum(sellNum);
                    goods.setRoleEquip(cloneRoleEquip);

                    int id = mallService.getRoleEquipId();
                    cloneRoleEquip.alterId(id);
                    cloneRoleEquip.alterGid(String.valueOf(id));
                    cloneRoleEquip.setId(id);
                } else {
                    goods.setRoleEquip(roleEquip);
                }
            }else {
                return;
            }
        }

        roleService.subtractMoney(role,  marketRent);

        if ("变身卡".equalsIgnoreCase(roleEquip.getType())) {
            SpringUtils.getBean(ChangeCardService.class).sendNullPosition(role, roleEquip.getPosition());
        }
        if (roleEquip.getName().contains("超级黑水晶·")) {
            int pos = roleEquip.queryEquipPos(true);
            FiedValue fieldValue = roleEquip.getFields().get((short) 514).getField().values().iterator().next();
            int maxValue = attrService.getFiledMax(fieldValue.getType(), roleEquip.queryLevel(), pos);
            int value = attrService.getValue(fieldValue.getValue());
            goods.setLevel(roleEquip.queryLevel());
            goods.setName(roleEquip.getName() + "|" + value + "|" + maxValue);
            goods.setType3(String.valueOf(roleEquip.queryLevel()));
        } else {
            goods.setName(roleEquip.getName());
        }

        NutMap nutMap = equipService.getRoleEquipBaiscInfo(roleEquip);
        goods.setLevel(roleEquip.queryLevel());
        goods.setPrice(req.getPrice());
        goods.setRoleId(role.getId());
        goods.setType1(roleEquip.getType());
        goods.setStartTime(new Date());
        goods.setNumber(req.getAmount());
        goods.setStartTime(new Date());
        goods.setNumber(1);

        goods.initSubType(nutMap);

        if (isPublicityItem(goods)) {
            goods.setShowEndTime(new Date(System.currentTimeMillis() + getShowEndTime()));
            goods.setEndTime(new Date(System.currentTimeMillis() + 3 * TimeUtil.ONE_DAY));
        } else {
            goods.setShowEndTime(new Date());
            goods.setEndTime(new Date(System.currentTimeMillis() + 2 * TimeUtil.ONE_DAY));
        }

        allGoods.put(goods.getId(), goods);
        Db4CommonService.getInstance().add2Queue(goods);


        initEquipAttr(goods, nutMap);

        sendGoodsList(role);
        role.save();
    }

    private void initEquipAttr(Goods goods, NutMap nutMap) {
        if (goods.getType1().equals("装备") || goods.getType1().equals("未鉴定装备")) {
            if (nutMap.getInt("menpaiYaoqiu") == 1) {
                goods.setType2("枪");
            } else if (nutMap.getInt("menpaiYaoqiu") == 2) {
                goods.setType2("爪");
            } else if (nutMap.getInt("menpaiYaoqiu") == 3) {
                goods.setType2("剑");
            } else if (nutMap.getInt("menpaiYaoqiu") == 4) {
                goods.setType2("扇");
            } else if (nutMap.getInt("menpaiYaoqiu") == 5) {
                goods.setType2("锤");
            }
            int sex = nutMap.getInt("sex");
            int peidai = nutMap.getInt("peidai");
            if (sex == 1) {
                String name = "男";
                if (peidai == 2) {
                    name = name + "帽";
                } else if (peidai == 3) {
                    name = name + "衣";
                }
                goods.setType2(name);
            } else if (sex == 2) {
                String name = "女";
                if (peidai == 2) {
                    name = name + "帽";
                } else if (peidai == 3) {
                    name = name + "衣";
                }
                goods.setType2(name);
            }
            if (peidai == 10) {
                goods.setType2("鞋");
            }
            goods.setLevel((short) nutMap.getInt("level1"));
        }
    }

    /**
     * 取集市最大摊位
     */
    public short getMaxStallNum(Role role) {
        short max = 4;
        if (role.isVip()) {
            if (role.getVipType() == 3) {
                max += 12;
            } else if (role.getVipType() == 2) {
                max += 8;
            } else if (role.getVipType() == 1) {
                max += 4;
            }
        }
        return max;
    }

    public void sendGoodsList(Role role) {
        RespStallMine respStallMine = new RespStallMine();
        respStallMine.setSellCash(role.getStallCash() + "");
        respStallMine.setStallTotalNum(getMaxStallNum(role));//摊位 VIP可增加

        List<Cargo> goodsList = new ArrayList<>();
        respStallMine.setList(goodsList);

        List<Goods> goods = queryMyGoods(role);
        for (Goods goods1 : goods) {
            Cargo cargo = new Cargo();
            if (goods1.getShowEndTime().after(new Date())) {
                cargo.setStartTime(new Long(goods1.getStartTime().getTime() / 1000).intValue());
                cargo.setEndTime(new Long(goods1.getShowEndTime().getTime() / 1000).intValue());
            } else {
                cargo.setStartTime(new Long(goods1.getShowEndTime().getTime() / 1000).intValue());
                cargo.setEndTime(new Long(goods1.getEndTime().getTime() / 1000).intValue());
            }
//           goods1.setLevel();
            cargo.setName(goods1.getName());
            cargo.setId(goods1.getMianbanId() + "");
            cargo.setAmount((short) goods1.getNumber());
            cargo.setPrice(goods1.getPrice());
            cargo.setInitPrice(goods1.getPrice());

            if (goods1.getShowEndTime().after(new Date())) {
                cargo.setStatus((short) 1);// 公示
            } else if (goods1.getEndTime().before(new Date())) {
                cargo.setStatus((short) 3);// 超时
            } else {
                cargo.setStatus((short) 2);// 在售
            }
            if (goods1.getType1().equals("宠物")) {
                Pet pet = goods1.getPet();
                if (pet == null) continue;
                NutMap nutMap = NutMap.NEW();
                nutMap.setv("enchant", pet.getEnchant());
                nutMap.setv("rank", pet.getType());
                nutMap.setv("mount_type", pet.getItype());
                if (pet.getMagRebuildLevel() == 0 && pet.getPhyRebuildLevel() == 0) {
                    nutMap.setv("rebuild_level", 0);// 0未强化 1强化
                } else {
                    nutMap.setv("rebuild_level", 1);// 0未强化 1强化
                }
                cargo.setPetLevel(pet.getLevel());
                nutMap.setv("eclosion", pet.getEclosion());//2羽化
                cargo.setExtra(Json.toJson(nutMap, JsonFormat.compact()));
            } else {
                if (goods1.getType1().equals("未鉴定装备")) {
                    cargo.setUnidentified((byte) 1);
                } else {
                    cargo.setUnidentified((byte) 0);
                }
            }
//          cargo.setIcon(goods1.get);
            goodsList.add(cargo);
        }
        respStallMine.setDealNum((short) 1);
        MessagePusher.pushMessage(role, respStallMine);
    }

    private List<Goods> queryMyGoods(Role role) {
        List<Goods> result = new ArrayList<>();
        for (Map.Entry<Long, Goods> entry : allGoods.entrySet()) {
            Goods goods = entry.getValue();
            if (goods.getRoleId() == role.getUid()) {
                result.add(goods);
            }
        }
        return result;
    }

    /**
     * 加载即使物品类型分类数据
     */
    public void loadCommonSet(Map<String, String> commonSetMap) {
        MarketDataPool.marketDatas = Json.fromJson(NutMap.class, commonSetMap.get("market_datas"));
    }

    public Goods getGoodsById(long goodsId) {
        return allGoods.get(goodsId);
    }

    /**
     * 查看名片
     */
    public void viewMarketCard(Role role, String status, String string) {
        if (isClosed) {
            RespMsg respMsg = new RespMsg();
            respMsg.setMsg("集市休市中。");
            MessagePusher.pushMessage(role, respMsg);
            return;
        }
        if(ServerService.neice!=100){
            if (role.getTotalCharge() <= minRechare || role.getLevel() < minLevel){

                MessagePusher.pushMessage(role,new RespNotifyMiscEx("没有充值或等级不足，无法使用集市功能！！"));
                return ;
            }
        }
        String[] statusArray = status.split("=");
        long gid = Long.parseLong(statusArray[1].split("\\|")[0]);
        
        Goods selectGoods = allGoods.get(gid);
        /**找不到时*/
        if (selectGoods == null) {
            MessagePusher.notify2Player(role, I18nId.PMT_1319);
            return ;
        }

        CardInfoParam cardInfoParam = Json.fromJson(CardInfoParam.class, string);

        byte type = (byte) (selectGoods.getShowEndTime().getTime() > new Date().getTime() ? 1 : 2);
        String sortKey = (type == 1 ? cardInfoParam.getShow_sort().getKey() : cardInfoParam.getSell_sort().getKey());
        byte sortType = (type == 1 ? cardInfoParam.getShow_sort().getType() : cardInfoParam.getSell_sort().getType());

        /**筛选出与所选同一分类中的所有物品并排序*/
        List<Goods> targetGoods = filterAndSortGoods(selectGoods.getType1(), selectGoods.getType2(),
                StringUtils.isNotEmpty(selectGoods.getType3()) ? selectGoods.getType3() : String.valueOf(selectGoods.getLevel()), type, sortKey, sortType);

        int index = 0;
        for (Goods goods : targetGoods) {
            if (goods.getId() == selectGoods.getId()) {break;}
            index ++;
        }
        /**从1开始计算，所以需要加1*/
        index += 1;
        int countPerPage = 8;
        int pageIndex = index /countPerPage + ((index % countPerPage == 0) ? 0 : 1);
        int maxPage = (int) Math.ceil((double) targetGoods.size() / countPerPage);
        pageIndex = Math.max(1, pageIndex);
        pageIndex = Math.min(pageIndex, maxPage);

        /**截出所选物品的那一页所有物品*/
        targetGoods = subSelectedPageGoods(targetGoods, countPerPage, pageIndex);

        RespStallList response = new RespStallList();
        response.setSort_key(sortKey);
        response.setIs_descending(sortType);
        String pathStr = getSelectedPathStr(selectGoods);
        response.setPath_str(pathStr);
        response.setTotalPage((short) maxPage);
        List<StallItem> list = getItemList(type, targetGoods);
        response.setList(list);
        response.setCurrPage((short) pageIndex);
        response.setSell_stage(type);
        response.setSelect_gid(String.valueOf(gid));

        MessagePusher.pushMessage(role, response);
    }

    /**
     * 筛选出与所选同一分类中的所有物品并排序
     */
    private List<Goods> filterAndSortGoods(String condition1, String condition2, String condition3, byte type, String sortKey, byte sortType) {
        List<Predicate<Goods>> conditions = filterConditions(condition1, condition2, condition3, type);
        Stream<Goods> stream = allGoods.values().stream();
        for (Predicate<Goods> predicate : conditions) {
            stream = stream.filter(predicate);
        }


        List<Goods> targetGoods = stream.collect(Collectors.toList());
        targetGoods.sort((o1, o2) -> {
            if (sortKey.equals("start_time")) {
                if (1 == sortType) {
                    // 升序
                    return o1.getStartTime().compareTo(o2.getStartTime());
                }
                return o2.getStartTime().compareTo(o1.getStartTime());
            }
            if (1 == sortType) {
                // 升序
                return o1.getPrice() - o2.getPrice();
            }
            return o2.getPrice() - o1.getPrice();
        });
        return targetGoods;
    }

    /**
     * 截出所选物品的那一页所有物品
     */
    private List<Goods> subSelectedPageGoods(List<Goods> targetGoods, int countPerPage, int pageIndex) {
        int startIndex = (pageIndex - 1) * countPerPage - 1;
        startIndex = Math.max(0, startIndex);
        int endIndex = startIndex + countPerPage;
        endIndex = Math.min(endIndex, targetGoods.size());
        targetGoods = targetGoods.subList(startIndex, endIndex);
        return targetGoods;
    }

    /**
     * 获得所选的便签路径
     */
    private String getSelectedPathStr(Goods selectGoods) {
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(selectGoods.getType1())) {
            sb.append(selectGoods.getType1());
        }
        if (StringUtils.isNotEmpty(selectGoods.getType2())) {
            if (sb.length() > 0) {sb.append("_");}
            sb.append(selectGoods.getType2());
        }
        if (StringUtils.isNotEmpty(selectGoods.getType3())) {
            if (sb.length() > 0) {sb.append("_");}
            sb.append(selectGoods.getType3());
        }
        return sb.toString();
    }

    private List<StallItem> getItemList(byte type, List<Goods> targetGoods) {
        List<StallItem> list = new ArrayList<>();
        for (Goods goods : targetGoods) {
            StallItem stallItem = new StallItem();
            stallItem.setName(goods.getName());
            stallItem.setName(goods.getName());
            stallItem.setId(goods.getMianbanId() + "");
            if (type == 1) {
                stallItem.setStatus((short) 1);
                stallItem.setEndTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
                stallItem.setStartTime(new Long(goods.getStartTime().getTime() / 1000).intValue());
            } else {
                stallItem.setEndTime(new Long(goods.getEndTime().getTime() / 1000).intValue());
                stallItem.setStartTime(new Long(goods.getShowEndTime().getTime() / 1000).intValue());
                stallItem.setStatus((short) 2);
            }
            stallItem.setPrice(goods.getPrice());
            stallItem.setReq_level(goods.getLevel() <= 1 ? 0 : goods.getLevel());
            stallItem.setAmount((short) goods.getNumber());
            if (goods.getType1().equals("未鉴定装备")) {
                stallItem.setUnidentified((byte) 1);
            } else {
                stallItem.setUnidentified((byte) 0);
            }
            if (goods.getType1().equals("宠物")) {
                Pet pet = goods.getPet();
                stallItem.setPetLevel(pet.getLevel());
                NutMap nutMap = NutMap.NEW();
                nutMap.setv("enchant", pet.getEnchant());
                nutMap.setv("rank", pet.getType());
                nutMap.setv("mount_type", pet.getItype());
                if (pet.getMagRebuildLevel() == 0 && pet.getPhyRebuildLevel() == 0) {
                    nutMap.setv("rebuild_level", 0);// 0未强化 1强化
                } else {
                    nutMap.setv("rebuild_level", 1);// 0未强化 1强化
                }
                nutMap.setv("eclosion", pet.getEclosion());//2羽化
                stallItem.setExtra(Json.toJson(nutMap, JsonFormat.compact()));
                stallItem.setItem_polar(goods.getXiangxin());
            } else if (goods.getType1().equals("法宝")) {
                stallItem.setItem_polar(goods.getXiangxin());
            }
            list.add(stallItem);
        }
        return list;
    }
}
